package com.bsoft.gol.hcs.his.service.impl;

import com.bsoft.gol.hcs.clinical.bean.req.QuerySampleTypeReq;
import com.bsoft.gol.hcs.clinical.bean.response.QuerySampleTypeResp;
import com.alibaba.fastjson.JSONObject;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.KeyGenerator;
import ctd.util.annotation.RpcService;
import ctd.util.xml.jaxb.JAXBUtils;
import com.bsoft.gol.hcs.enumcase.CrucialTypeEnum;
import com.bsoft.gol.hcs.enumcase.InspectionEmum;
import hcn.base.Organization;
import hcn.util.BaseResponse;
import com.bsoft.gol.hcs.his.bean.crucial.his.inner.ExamClassifyRecordLists;
import com.bsoft.gol.hcs.his.bean.crucial.his.inner.entity.CrucialIndexRecord;
import com.bsoft.gol.hcs.his.bean.crucial.his.inner.entity.InspectClassifyRecord;
import com.bsoft.gol.hcs.his.bean.crucial.his.inner.entity.ResultNatureRecord;
import com.bsoft.gol.hcs.his.bean.crucial.his.outer.ExamClassifyRecordResp;
import com.bsoft.gol.hcs.his.bean.crucial.his.outer.InspectClassifyRecordResp;
import com.bsoft.gol.hcs.his.bean.crucial.his.outer.QueryCrucialRecordResp;
import com.bsoft.gol.hcs.his.bean.crucial.his.outer.QueryCrucialResultRecordResp;
import com.bsoft.gol.hcs.his.bean.crucial.his.req.QueryExamClassifyRequest;
import com.bsoft.gol.hcs.his.bean.crucial.his.req.QueryInspectIndexRequest;
import com.bsoft.gol.hcs.his.bean.crucial.request.QueryCrucialRecordRequest;
import com.bsoft.gol.hcs.his.bean.crucial.response.*;
import com.bsoft.gol.hcs.his.service.ICrucialHisService;
import com.bsoft.gol.hcs.his.service.IInspectionHisXMLService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import service.rpc.impl.OrganizationRpcServiceImpl;
import com.bsoft.gol.hcs.utils.BaseRespUtil;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.JSONDateUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

import static com.bsoft.gol.hcs.utils.WhisClientUtil.*;


/**
 * @Author: lanyu
 * @Description: his关联指标service实现
 * @Date: create in 2022/7/12 11:14
 */
@SsdevService("crucialHisService")
public class CrucialHisServiceImpl implements ICrucialHisService {
    private final static Logger log = LoggerFactory.getLogger(CrucialHisServiceImpl.class);
    private final static String ORIGINORG = "1";
    @Value("${project_source}")
    private String proSource;
    @Value("${phis_path_url}")
    public String PHIS_PATH_URL;

    @Autowired
    IInspectionHisXMLService inspectionHisXMLService;
    @Autowired
    OrganizationRpcServiceImpl organizationRpcService;

    /**
     * 同步关联指标信息
     *
     * @param request
     * @return
     */
    @RpcService
    @Override
    public BaseResponse syncCrucialIndexRecordHis(QueryCrucialRecordRequest request) {
        BaseResponse baseResponse = new BaseResponse();
        log.info("syncCrucialIndexRecordHis-入参=>>>" + request.toString() + "=====");
        //TODO 测试数据

//        String serviceName = InspectionEmum.getValue("ODS_CrucialBatchQuery");
//        String service = InspectionEmum.QueryCrucialRecord.getCode();
//        String msgType = serviceName;
//        String msgHeaderXml = getMsgHeaderXml(ORIGINORG, "PHIS", msgType);
//        String xml = JAXBUtils.object2Xml(QueryCrucialRecordRequest.class, request);
//        String new_xml = msgHeaderXml + xml;
//        String requestXml = getSoapXml(service, new_xml);
//        log.info("入参：{}", requestXml);
//        try {
//            CrucialIndexRecordList crucialIndexRecords = null;
//            String resultXml = getStringDataFromPhis(PHIS_PATH_URL, requestXml);
//            QueryCrucialRecordResp xml2Object = JAXBUtils.xml2Object(resultXml, QueryCrucialRecordResp.class);
//            if (CommonUtils.isNotEmpty(xml2Object) && CommonUtils.isNotEmpty(xml2Object.getMsgBody())) {
//                if ("true".equals(xml2Object.getMsgBody().getStatus())) {//返回成功
//                    if (CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData()) && CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData())) {
//                        crucialIndexRecords = xml2Object.getMsgBody().getData();
//                        CrucialIndexResultResponse crucialIndexResultResponse = this.transformCrucialEntity(crucialIndexRecords);
//                        baseResponse.setData(crucialIndexResultResponse);
//                    }
//                } else {
//                    baseResponse = BaseRespUtil.setResultError(xml2Object.getMsgBody().getDetail());
//                }
//            }
//        } catch (Exception e) {
//            baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");
//            return baseResponse;
//        }
        //TODO 模拟数据
        String crucialIndex = JSONDateUtils.readFile("crucialIndex");
        List<CrucialIndexHisResponse> crucialIndexHisResponses = JSONObject.parseArray(crucialIndex, CrucialIndexHisResponse.class);
        String crucialType = JSONDateUtils.readFile("crucialType");
        List<IndexClassifyResponse> indexClassifyResponses = JSONObject.parseArray(crucialType, IndexClassifyResponse.class);
        String sampleType = JSONDateUtils.readFile("sampleType");
        List<SimpleIndexResponse> simpleIndexResponses = JSONObject.parseArray(sampleType, SimpleIndexResponse.class);
        String measureMode = JSONDateUtils.readFile("measureMode");
        List<MeasureModeResponse> measureModeResponses = JSONObject.parseArray(measureMode, MeasureModeResponse.class);
        CrucialIndexResultResponse crucialIndexResultResponse = new CrucialIndexResultResponse();
        crucialIndexResultResponse.setCrucialIndexResponses(crucialIndexHisResponses);
        crucialIndexResultResponse.setIndexClassifyResponses(indexClassifyResponses);
        crucialIndexResultResponse.setSimpleIndexResponses(simpleIndexResponses);
        crucialIndexResultResponse.setMeasureModeResponses(measureModeResponses);
        baseResponse.setData(crucialIndexResultResponse);
        baseResponse.setCode(200);
        return baseResponse;
    }

    /**
     * 同步检验指标信息
     *
     * @param request
     * @return
     * @throws ControllerException
     */
    @Override
    public BaseResponse syncInspectCrucialRecordsHis(QueryCrucialRecordRequest request) throws ControllerException {
        String serviceName = InspectionEmum.getValue("LabReportItemListQuery");
        String service = "ODS_" + InspectionEmum.LabReportItemListQuery.getCode();
        String msgType = "ODS_" + serviceName;
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG, proSource, msgType);
        String serviceCode = "<service>" + InspectionEmum.LabReportItemListQuery.getCode() + "</service>";
        BaseResponse baseResponse = new BaseResponse();
        //转化为xml
        QueryInspectIndexRequest inspectIndexRequest = new QueryInspectIndexRequest();
        inspectIndexRequest.setVisitOrganization(request.getOrganizationId());
        inspectIndexRequest.setPageNo(request.getPageNo());
        inspectIndexRequest.setPageSize(request.getPageSize());
        String xml = JAXBUtils.object2Xml(QueryInspectIndexRequest.class, inspectIndexRequest);
        String new_xml = msgHeaderXml + "<MsgBody>" + serviceCode + xml + "</MsgBody>";
        String requestXml = getSoapXml(service, new_xml);
        log.info("入参：{}", requestXml);
        try {
            String resultXml = getStringDataFromPhis(PHIS_PATH_URL, requestXml);
            QueryCrucialRecordResp xml2Object = JAXBUtils.xml2Object(resultXml, QueryCrucialRecordResp.class);
            if (CommonUtils.isNotEmpty(xml2Object) && CommonUtils.isNotEmpty(xml2Object.getMsgBody())) {
                List<CrucialIndexHisResponse> list = new ArrayList<>();
                if ("true".equals(xml2Object.getMsgBody().getStatus())) {
                    if (CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData()) && CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData())) {
                        List<CrucialIndexRecord> indexList = xml2Object.getMsgBody().getData().getReportItemLists().getReportItemList();
                        list = this.transformInspectCrucialRecord(indexList, request.getOrganizationId());
                        baseResponse.setData(list);
                    }
                } else {
                    baseResponse.setData(list);
                    //baseResponse = BaseRespUtil.setResultError(xml2Object.getMsgBody().getDetail());
                }
            }
        } catch (Exception e) {
            baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");
            return baseResponse;
        }
        return baseResponse;
    }

    /**
     * 检验指标数据实体转化
     *
     * @param indexLists
     * @return
     */
    private List<CrucialIndexHisResponse> transformInspectCrucialRecord(List<CrucialIndexRecord> indexLists, String organizationId) {
        List<CrucialIndexHisResponse> crucialIndexHisResponses = new ArrayList<>();
        if (CommonUtils.isNotEmpty(indexLists)) {
            crucialIndexHisResponses = indexLists.stream().map((indexList) -> {
                CrucialIndexHisResponse crucial = new CrucialIndexHisResponse();
                crucial.setIndexId(indexList.getTestId());
                crucial.setIndexCode(indexList.getTestCode());
                crucial.setIndexName(indexList.getTestName());
                crucial.setOrganizationId(organizationId);
                //这里获取机构名称
                Organization organization = organizationRpcService.getOrgDetailByOrgCode(organizationId);
                crucial.setOrganizationName(organization.getFullName());
                crucial.setIndexType(CrucialTypeEnum.INSPECT.getType());
                crucial.setPinyinCode(indexList.getInputCode());
                crucial.setIndexAbbreviation(indexList.getTestEnglishAb());
                crucial.setSampleType(indexList.getSampleTypeCode());
                crucial.setSampleName(indexList.getSampleTypeName());
                crucial.setIndexClassifyId(indexList.getIndexClassifyId());
                crucial.setIndexClassifyName(indexList.getIndexClassifyName());
                crucial.setSignificantDigits(indexList.getSignificantDigits());
                crucial.setUnit(indexList.getUnit());
                return crucial;
            }).collect(Collectors.toList());
            //根据指标id进行去重
            crucialIndexHisResponses = crucialIndexHisResponses.stream().collect(
                    Collectors.collectingAndThen(Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(CrucialIndexHisResponse::getIndexId))),
                            ArrayList::new));
        }
        return crucialIndexHisResponses;
    }

    /**
     * 同步检验分类信息
     *
     * @param request
     * @return
     * @throws ControllerException
     */
    @Override
    public BaseResponse syncInspectClassifyRecordsHis(QueryCrucialRecordRequest request) throws ControllerException {
        BaseResponse baseResponse = new BaseResponse();
        String serviceName = InspectionEmum.getValue("InspectClassifyItemListQuery");
        String service = "ODS_" + InspectionEmum.InspectClassifyItemListQuery.getCode();
        String msgType = "ODS_" + serviceName;
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG, proSource, msgType);
        String serviceCode = "<service>" + InspectionEmum.InspectClassifyItemListQuery.getCode() + "</service>";
        //转化为xml
        request.setPageSize(400);
        QueryInspectIndexRequest inspectIndexRequest = new QueryInspectIndexRequest();
        inspectIndexRequest.setVisitOrganization(request.getOrganizationId());
        inspectIndexRequest.setPageNo(request.getPageNo());
        inspectIndexRequest.setPageSize(request.getPageSize());
        String xml = JAXBUtils.object2Xml(QueryInspectIndexRequest.class, inspectIndexRequest);
        String new_xml = msgHeaderXml + "<MsgBody>" + serviceCode + xml + "</MsgBody>";
        String requestXml = getSoapXml(service, new_xml);
        log.info("入参：{}", requestXml);
        try {
            String resultXml = getStringDataFromPhis(PHIS_PATH_URL, requestXml);
            InspectClassifyRecordResp xml2Object = JAXBUtils.xml2Object(resultXml, InspectClassifyRecordResp.class);
            if (CommonUtils.isNotEmpty(xml2Object) && CommonUtils.isNotEmpty(xml2Object.getMsgBody())) {
                if ("true".equals(xml2Object.getMsgBody().getStatus())) {
                    if (CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData()) && CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData())) {
                        List<InspectClassifyRecord> indexClassifyList = xml2Object.getMsgBody().getData().getIndexClassifyLists().getIndexClassifyList();
                        List<InspectClassifyResponse> list = this.transformInspectClassifyRecord(indexClassifyList, request.getOrganizationId());
                        baseResponse.setData(list);
                    }
                } else {
                    baseResponse = BaseRespUtil.setResultError(xml2Object.getMsgBody().getDetail());
                }
            }
        } catch (Exception e) {
            baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");
            return baseResponse;
        }
        return baseResponse;
//        String crucialType = JSONDateUtils.readFile("inspectClassifyRecord");
//        List<InspectClassifyResponse> inspectClassifyResponses = JSONObject.parseArray(crucialType, InspectClassifyResponse.class);
//        baseResponse.setData(inspectClassifyResponses);
//        return baseResponse;
    }

    /**
     * 检验分类转换实体类
     *
     * @param indexClassifyList
     * @param organizationId
     * @return
     */
    private List<InspectClassifyResponse> transformInspectClassifyRecord(List<InspectClassifyRecord> indexClassifyList, String organizationId) {
        List<InspectClassifyResponse> responses = new ArrayList<>();
        if (CommonUtils.isNotEmpty(indexClassifyList)) {
            responses = indexClassifyList.stream().map((index) -> {
                InspectClassifyResponse inspectClassify = new InspectClassifyResponse();
                BeanUtils.copyProperties(index, inspectClassify);
                return inspectClassify;
            }).collect(Collectors.toList());
        }
        return responses;
    }

    /**
     * 同步检验样本信息
     *
     * @param request
     * @return
     * @throws ControllerException
     */
    @Override
    public BaseResponse syncInspectSampleRecordsHis(QueryCrucialRecordRequest request) throws ControllerException {
        BaseResponse baseResponse = new BaseResponse();
        QuerySampleTypeReq querySampleTypeReq = new QuerySampleTypeReq();
        querySampleTypeReq.setOrganizationId(request.getOrganizationId());
        querySampleTypeReq.setInspectionItemId(null);
        BaseResponse<List<QuerySampleTypeResp>> baseResponse1 = inspectionHisXMLService.querySampleTypeXML(querySampleTypeReq);
//        String sampleType = JSONDateUtils.readFile("sampleType");
//        List<SimpleIndexResponse> simpleIndexResponses = JSONObject.parseArray(sampleType, SimpleIndexResponse.class);
//        baseResponse.setData(simpleIndexResponses);
        if (CommonUtils.isNotEmpty(baseResponse1.getData())) {
            List<QuerySampleTypeResp> sampleList = baseResponse1.getData();
            List<SimpleIndexResponse> collect = sampleList.stream().map((sample) -> {
                SimpleIndexResponse indexResponse = new SimpleIndexResponse();
                indexResponse.setSimpleId(KeyGenerator.randomGenerate());
                indexResponse.setSimpleName(sample.getSpecimenTypeName());
                indexResponse.setSimpleType(sample.getSpecimenTypeId());
                return indexResponse;
            }).collect(Collectors.toList());
            baseResponse.setData(collect);
        }
        return baseResponse;
    }

    /**
     * 同步检查分类信息
     *
     * @param request
     * @return
     * @throws ControllerException
     */
    @Override
    public BaseResponse syncExamClassifyRecordsHis(QueryCrucialRecordRequest request) throws ControllerException {
        BaseResponse baseResponse = new BaseResponse();
        String serviceName = InspectionEmum.getValue("ODS_getExamTypeList_WHIS");
        String service = InspectionEmum.ExamClassifyRecords.getCode();
        String msgType = serviceName;
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG, "PHIS", msgType);
        QueryExamClassifyRequest examClassifyRequest = new QueryExamClassifyRequest();
        examClassifyRequest.setExamExecuteOrgId(request.getOrganizationId());
        String xml = JAXBUtils.object2Xml(QueryExamClassifyRequest.class, examClassifyRequest);
        String new_xml = msgHeaderXml + "<MsgBody>" + xml + "</MsgBody>";
        String requestXml = getSoapXml(service, new_xml);
        log.info("入参：{}", requestXml);
        try {
            String resultXml = getStringDataFromPhis(PHIS_PATH_URL, requestXml);
            ExamClassifyRecordResp xml2Object = JAXBUtils.xml2Object(resultXml, ExamClassifyRecordResp.class);
            if (CommonUtils.isNotEmpty(xml2Object) && CommonUtils.isNotEmpty(xml2Object.getMsgBody())) {
                if ("true".equals(xml2Object.getMsgBody().getStatus())) {//返回成功
                    if (CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData()) && CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData())) {
                        ExamClassifyRecordLists examTypes = xml2Object.getMsgBody().getData().getExamTypes();
                        List<ExamClassifyResponse> examClassifyResponse = this.transformExamClassifyRecord(examTypes);
                        baseResponse.setData(examClassifyResponse);
                    }
                } else {
                    baseResponse = BaseRespUtil.setResultError(xml2Object.getMsgBody().getDetail());
                }
            }
        } catch (Exception e) {
            baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");
            return baseResponse;
        }
//        String crucialType = JSONDateUtils.readFile("examClassifyRecord");
//        List<ExamClassifyResponse> inspectClassifyResponses = JSONObject.parseArray(crucialType, ExamClassifyResponse.class);
//        baseResponse.setData(inspectClassifyResponses);
        return baseResponse;
    }

    /**
     * 检查分类转换实体类
     *
     * @param examTypes
     * @return
     */
    private List<ExamClassifyResponse> transformExamClassifyRecord(ExamClassifyRecordLists examTypes) {
        List<ExamClassifyResponse> examClassifyResponses = new ArrayList<>();
        if (CommonUtils.isNotEmpty(examTypes.getExamType())) {
            examClassifyResponses = examTypes.getExamType().stream().map((examType) -> {
                ExamClassifyResponse examClassify = new ExamClassifyResponse();
                BeanUtils.copyProperties(examType, examClassify);
                return examClassify;
            }).collect(Collectors.toList());
        }
        return examClassifyResponses;
    }

    /**
     * 同步结果性质信息
     *
     * @param request
     * @return
     * @throws ControllerException
     */
    @Override
    public BaseResponse syncCrucialResultRecordHis(QueryCrucialRecordRequest request) throws ControllerException {
        BaseResponse baseResponse = new BaseResponse();
        log.info("syncCrucialResultRecordHis-入参=>>>" + request.toString() + "=====");
        String serviceName = InspectionEmum.getValue("InspectResultNatureItemListQuery");
        String service = "ODS_" + InspectionEmum.QueryCrucialResultRecord.getCode();
        String msgType = "ODS_" + serviceName;
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG, proSource, msgType);
        String serviceCode = "<service>" + InspectionEmum.QueryCrucialResultRecord.getCode() + "</service>";
        //转化为xml
        QueryInspectIndexRequest inspectIndexRequest = new QueryInspectIndexRequest();
        inspectIndexRequest.setVisitOrganization(request.getOrganizationId());
        inspectIndexRequest.setPageNo(request.getPageNo());
        inspectIndexRequest.setPageSize(request.getPageSize());
        String xml = JAXBUtils.object2Xml(QueryInspectIndexRequest.class, inspectIndexRequest);
        String new_xml = msgHeaderXml + "<MsgBody>" + serviceCode + xml + "</MsgBody>";
        String requestXml = getSoapXml(service, new_xml);
        log.info("入参：{}", requestXml);
        try {
            String resultXml = getStringDataFromPhis(PHIS_PATH_URL, requestXml);
            QueryCrucialResultRecordResp xml2Object = JAXBUtils.xml2Object(resultXml, QueryCrucialResultRecordResp.class);
            if (CommonUtils.isNotEmpty(xml2Object) && CommonUtils.isNotEmpty(xml2Object.getMsgBody())) {
                if ("true".equals(xml2Object.getMsgBody().getStatus())) {
                    if (CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData()) && CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData())) {
                        List<ResultNatureRecord> crucialResultRecord = xml2Object.getMsgBody().getData().getResultNatureLists().getResultNatureList();
                        //TODO 需要将his的数据转换
                        List<CrucialResultNature> crucialResultNatures = this.transformResultNatureRecord(crucialResultRecord);
                        baseResponse.setData(crucialResultNatures);
                    }
                } else {
                    baseResponse = BaseRespUtil.setResultError(xml2Object.getMsgBody().getDetail());
                }
            }
        } catch (Exception e) {
            baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");
            return baseResponse;
        }
        return baseResponse;
        //TODO 模拟数据
//        String resultNature = JSONDateUtils.readFile("resultNature");
//        List<CrucialResultNature> crucialResultNatures = JSONObject.parseArray(resultNature, CrucialResultNature.class);
//        baseResponse.setData(crucialResultNatures);
//        baseResponse.setCode(200);
//        return baseResponse;
    }

    /**
     * @param crucialResultRecord
     * @return
     */
    private List<CrucialResultNature> transformResultNatureRecord(List<ResultNatureRecord> crucialResultRecord) {
        List<CrucialResultNature> crucialResultNatures = new ArrayList<>();
        if (CommonUtils.isNotEmpty(crucialResultRecord)) {
            for (ResultNatureRecord resultNatureRecord : crucialResultRecord) {
                CrucialResultNature crucialResultNature = new CrucialResultNature();
                if (CommonUtils.isNotEmpty(resultNatureRecord.getNatureLists())) {
                    List<ResultNatureRecord.NatureLists.NatureList> natureLists = resultNatureRecord.getNatureLists().getNatureList();
                    if (CommonUtils.isNotEmpty(natureLists)) {
                        List<CrucialResultNature> collect = natureLists.stream().map((natureList) -> {
                            CrucialResultNature nature = new CrucialResultNature();
                            nature.setResultNatureCode(natureList.getNatureCode());
                            nature.setResultNatureValue(natureList.getNatureName());
                            return nature;
                        }).collect(Collectors.toList());
                        crucialResultNature.setResultNatureList(collect);
                    }
                }
                BeanUtils.copyProperties(resultNatureRecord, crucialResultNature);
                crucialResultNatures.add(crucialResultNature);
            }
        }
        return crucialResultNatures;
    }

}
